import React, { useEffect, useState } from "react";
import { NavBar, Space, Toast } from "antd-mobile";
import { HeartOutline, HeartFill } from "antd-mobile-icons";
import { useParams, useNavigate } from "react-router-dom";
import { courseDetailGet } from "../../api/course";
import { CourseType } from "../../type/course";
import "./index.scss";
import { useUserStore } from "../../store/user";
import { collectDel, collectGet, collectPost } from "../../api/user";
export interface IDetailProps {}

export default function Detail(props: IDetailProps) {
  const [detail, setDetail] = useState<CourseType>();
  const [collect, setCollect] = useState<boolean>(false);
  const [collectId, setCollectId] = useState<string>("");
  const params = useParams();
  const navigate = useNavigate();
  const { userInfo } = useUserStore((state) => state);
  useEffect(() => {
    let { id } = params;
    // console.log(id);
    // 加载详情
    courseDetailGet(id as string).then((res) => {
      console.log(res);
      setDetail(res.data);
    });
    // 初始化收藏状态
    if (userInfo) {
      collectGet(userInfo.objectId, id as string).then((res) => {
        let { results } = res.data;
        if (results.length) {
          setCollect(true);
          setCollectId(results[0].objectId); //记录收藏id
        }
      });
    }
  }, []);
  const handleCollect = () => {
    console.log(1111);

    if (!userInfo) {
      console.log(2222);
      navigate(`/login`);
      return;
    }
    let userid = userInfo.objectId;
    let courseid = detail!.objectId;
    let { name, poster, isvip } = detail as CourseType;
    collectPost({ userid, courseid, name, poster, isvip }).then((res) => {
      setCollect(true);
      setCollectId(res.data.objectId); //记录收藏id
    });
  };
  const handleUnCollect = () => {
    if (!userInfo) {
      navigate(`/login?target=/detail/${detail?.objectId}`);
      return;
    }
    collectDel(collectId).then((res) => {
      setCollect(false);
    });
  };
  const right = (
    <div style={{ fontSize: 24 }}>
      {collect ? (
        <HeartFill color="#4D6BD1" onClick={handleUnCollect} />
      ) : (
        <HeartOutline onClick={handleCollect} />
      )}
    </div>
  );

  const back = () => {
    navigate(-1);
  };
  return (
    <div>
      <NavBar right={right} onBack={back}>
        课程详情
      </NavBar>
      <div className="detail">
        {/* <img src={detail?.poster} alt="" /> */}
        <h3>{detail?.name}</h3>
        <div dangerouslySetInnerHTML={{ __html: detail?.desc as string }}></div>
      </div>
    </div>
  );
}
